'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import type { IDifference } from '@/interfaces';
import { createMenu } from '@/services/api';
import { useMutation } from '@tanstack/react-query';
import diff from 'microdiff';
import useToast from '@/hooks/useToast';
import { clearFormData, getDiffData } from '@/lib/tool';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import Box from '@/app/[locale]/admin/common/box';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function CreateMenuAdminPage({
  source,
  translatedFields,
}: {
  source?: any;
  translatedFields: PrefixedTTranslatedFields<'menuAdminPage'>;
}) {
  const [form, setForm] = useState({
    name: '',
    path: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const { show } = useToast();
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const createMenuMutation = useMutation(createMenu);

  useEffect(() => {
    const diffData = diff(
      {
        name: '',
        path: '',
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form]);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();
      const data = getDiffData(differenceData) as any;
      await createMenuMutation.mutateAsync({
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.saveCompleted,
      });
    } catch (e) {
      createMenuMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setForm(clearFormData(form));
      setDifferenceData([]);
    }
  }

  function checkForm() {
    const { name, path } = form;

    if (!name) {
      throw translatedFields.tip.nameRequired;
    }

    if (!path) {
      throw translatedFields.tip.pathRequired;
    }
  }

  function onChangeForm(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  return (
    <Box>
      <form onSubmit={onSubmit} className="vstack gap-4">
        <div>
          <label className="form-label">
            {translatedFields.properties.name}
          </label>
          <input
            type="text"
            className="form-control"
            name="name"
            value={form.name}
            onChange={onChangeForm}
          ></input>
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.path}
          </label>
          <input
            type="text"
            className="form-control"
            name="path"
            value={form.path}
            onChange={onChangeForm}
          ></input>
        </div>

        <button
          type="submit"
          disabled={createMenuMutation.isLoading || isDisabledSave}
          className="btn btn-primary col col-lg-2 mt-4"
        >
          {createMenuMutation.isLoading && <Spinner classs="me-2" />}
          {translatedFields.operate.save}
        </button>
      </form>
    </Box>
  );
}
